var bmap = require("../../../utils/bmap-wx.min");

// pages/index/map/map.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    input: "",
    longitude: "116.397469",
    latitude: "39.908821",
    markers: [],
    sugData: "",
    weatherData: "",
    showHotWord: false,
    timer: null,
  },

  // 获取地理位置
  getLocation() {
    const that = this;
    wx.getLocation({
      type: "gcj02",
      success: (res) => {
        // console.log(res);
        wx.showToast({
          title: "已定位到当前位置",
          icon: "none",
        });
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude,
        });
      },
      fail: (err) => {
        wx.showToast({
          title: "位置获取失败",
          icon: "none",
        });
        // this.baiduMap("北京市故宫博物院");
        that.chooseLocation();
        // that.setData({
        //     longitude: '116.397469',
        //     latitude: '39.908821',
        // })
      },
    });
  },

  //   授权位置
  chooseLocation() {
    const that = this;
    wx.getSetting({
      success: (result) => {
        if (
          result.authSetting["scope.userLocation"] != undefined &&
          result.authSetting["scope.userLocation"] != true
        ) {
          wx.showModal({
            title: "是否授权当前位置",
            content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
            success: function (res) {
              if (res.cancel) {
                wx.navigateBack();
                wx.showToast({
                  title: "授权失败",
                  icon: "error",
                });
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (data) {
                    // console.log(data);
                    if (data.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: "授权成功",
                        icon: "success",
                      });
                      //再次授权，调用getLocationt的API
                      that.getLocation();
                    } else {
                      wx.showToast({
                        title: "授权失败",
                        icon: "none",
                      });
                    }
                  },
                });
              }
            },
          });
        }
      },
      fail: () => { },
      complete: () => { },
    });
  },

  searchInput(e) {
    var that = this;
    let { timer } = that.data;
    this.setData({
      input: e.detail.value,
    });

    // let timer = null
    clearTimeout(timer);
    timer = setTimeout(() => {
      if (e.detail.value) {
        this.setData({
          showHotWord: true,
        });
      } else {
        this.setData({
          showHotWord: false,
        });
      }
      var BMap = new bmap.BMapWX({
        ak: "jqvSKSPxtKLsck0nihZqCqds4pPGhXfK",
      });
      // 发起suggestion检索请求
      BMap.suggestion({
        query: e.detail.value,
        // region: '北京',
        city_limit: true,
        fail: (err) => {
          console.log(err);
        },
        success: (data) => {
          // console.log(data.result);
          that.setData({
            sugData: data.result,
          });
        },
      });
    }, 200);

    that.setData({
      timer,
    });
  },

  search() {
    const { input } = this.data;
    // this.requestMap(input)
    this.baiduMap(input);
    // this.setData({
    //     input: ''
    // })
  },

  sureAddress(e) {
    const { name, address, longitude, latitude } = e.currentTarget.dataset;
    this.openLocation(latitude, longitude, name, address);
    this.setData({
      input: name,
      showHotWord: false,
      longitude,
      latitude,
      markers: [
        {
          id: 0,
          alpha: 1,
          latitude,
          longitude,
          iconPath: "/static/icon/map/dingweiweizhi_1.png",
          iconTapPath: "/static/icon/map/dingweiweizhi_1.png",
          height: "50rpx",
          width: "50rpx",
        },
      ],
    });
    // this.baiduMap(name);
  },

  // 腾讯地图API
  requestMap(address) {
    const that = this;
    wx.request({
      url: "https://apis.map.qq.com/ws/geocoder/v1",
      data: {
        key: "PPDBZ-3H56W-OLURE-YS7M7-VDVEZ-PIFCS",
        address,
      },
      header: {
        "content-type": "application/json", // 默认值
      },
      success(res) {
        if (res.status == 0) {
          const { location } = res.res.result;
          that.setData({
            longitude: location.lng,
            latitude: location.lat,
          });
        } else {
          wx.showToast({
            title: "请求失败",
            icon: "none",
          });
        }

        // console.log(res.data)
      },
    });
  },

  // 百度地图API
  baiduMap(address) {
    var that = this;
    // 新建百度地图对象
    var BMap = new bmap.BMapWX({
      ak: "jqvSKSPxtKLsck0nihZqCqds4pPGhXfK",
    });
    // 发起geocoding检索请求
    BMap.geocoding({
      address,
      success: (res) => {
        // console.log(res);
        if (res.status == 0) {
          const { location } = res.result;
          that.openLocation(location.lat, location.lng, address, '');
          // console.log(location);
          res.wxMarkerData.forEach((i) => {
            i.width = "50rpx";
            i.height = "50rpx";
          });
          // res.wxMarkerData[0].width = '10rpx',
          // res.wxMarkerData[0].height = '10rpx',
          that.setData({
            longitude: location.lng,
            latitude: location.lat,
            markers: res.wxMarkerData,
            showHotWord: false
          });
        } else {
          wx.showToast({
            title: "请求失败",
            icon: "none",
          });
        }
      },
      fail: (err) => {
        console.log(err);
      },
      iconPath: "/static/icon/map/dingweiweizhi_1.png",
      iconTapPath: "/static/icon/map/dingweiweizhi_1.png",
    });
  },

  openLocation(latitude, longitude, name, address) {
    wx.openLocation({
      latitude, // 纬度
      longitude, // 经度
      name, // 地点名称
      address, // 地址的详细说明
      scale: 18, // 缩放比例
      success: function (res) {
        console.log('打开地图成功');
      },
      fail: function (err) {
        console.log('打开地图失败', err);
      }
    });
  },

  makertap(e) {
    console.log(e);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.getWeather();
    this.getLocation();
    // this.baiduMap('北京市故宫博物院')
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
});
